const { Pool } = require('pg');
const fs = require('fs');
const path = require('path');

// 创建数据库连接池
const pool = new Pool({
  user: 'postgres',
  host: 'localhost',
  database: 'math',
  password: '123456',
  port: 5432,
});

async function initDatabase() {
  try {
    console.log('确保数据库存在...');

    // 读取schema.sql文件内容
    const schemaPath = path.join(__dirname, 'schema.sql');
    const schemaSql = fs.readFileSync(schemaPath, 'utf8');

    // 执行SQL脚本
    await pool.query(schemaSql);

    // 确保管理员账号存在，并且密码是明文'123456'
    const adminCheck = await pool.query(
      "SELECT id FROM users WHERE username = 'admin'"
    );

    if (adminCheck.rows.length === 0) {
      // 创建管理员用户
      await pool.query(
        `INSERT INTO users (username, email, password_hash, role, status) 
         VALUES ('admin', 'admin@school.edu', '123456', 'admin', 'approved')`
      );
      console.log('管理员账号创建成功');
    } else {
      // 更新现有管理员密码
      await pool.query(
        `UPDATE users SET password_hash = '123456' WHERE username = 'admin'`
      );
      console.log('管理员密码已更新');
    }

    console.log('数据库表结构创建成功！');

  } catch (error) {
    console.error('初始化数据库错误:', error);
  } finally {
    pool.end();
  }
}

initDatabase(); 